<template>
  <div>
    <li :class="{completed: todo.completed, editing: todo.id === editId}">
      <div class="view">
        <input type="checkbox" v-model="todo.completed">
        <label @dblclick="editTodo(todo)">{{ todo.title }}</label>
        <button @click="removeTodo(todo)">x</button>
      </div>
      <EditTodo class="edit"
                v-model:todoTitle="todo.title"
                @blur="doneEdit(todo)"
                @keyup.enter="doneEdit(todo)"
                @keyup.esc="cancelEdit(todo)"
                v-todo-focus="todo.id === editId"
      ></EditTodo>
    </li>
  </div>
</template>

<script>
import {reactive, toRefs} from 'vue'

export default {
  directives: {
    'todo-focus': (el, {value}) => {
      if (value) {
        el.focus()
      }
    }
  },
  props: {
    todo: {
      type: Object,
      require: true
    },
    editId: String, Number
  },
  emits: ['removeTodo', 'update:editId'],
  setup(props, {emit}) {
    const state = reactive({
      beforeContent: ''
    })

    function removeTodo(item) {
      emit('removeTodo', item)
    }

    function editTodo(item) {
      state.beforeContent = item.title
      emit('update:editId', item.id)
    }

    function doneEdit() {
      emit('update:editId', null)
    }

    function cancelEdit(item) {
      item.title = state.beforeContent
      emit('update:editId', null)
    }

    return {
      ...toRefs(state),
      cancelEdit,
      doneEdit,
      editTodo,
      removeTodo
    }
  }
}
</script>

<style scoped>
.completed label {
  text-decoration: line-through;
}

.edit {
  display: none;
}

.editing .view {
  display: none;
}

.editing .edit {
  display: block;
}
</style>
